package aa.jx.order.service.impl;


import aa.jx.order.mapper.OrderItemMapper;
import aa.jx.order.mapper.OrderMapper;
import aa.jx.order.mapper.PaymentMapper;
import aa.jx.order.mapper.ProductMapper;
import aa.jx.order.model.*;
import aa.jx.order.service.OrderService;
import aa.jx.order.model.Product;
import aa.jx.register.mapper.AddressMapper;
import aa.jx.register.model.Address;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private AddressMapper addressMapper;

    @Override
    @Transactional
    public Order createOrder(Integer userId, Integer addressId, List<OrderItem> cartItems) {
        // 验证地址
        Address address = addressMapper.selectById(addressId);
        if (address == null || address.getUserId()!=userId) {
            throw new RuntimeException("无效的收货地址");
        }

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem item : cartItems) {
            Product product = productMapper.selectById(item.getProductId().intValue());
            if (product == null || product.getStock() < item.getQuantity()) {
                throw new RuntimeException("商品库存不足: " + (product != null ? product.getName() : "未知商品"));
            }
            item.setProductPrice(product.getPrice());
            item.setTotalPrice(item.getProductPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            totalAmount = totalAmount.add(item.getTotalPrice());
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setPaymentAmount(totalAmount); // 假设无优惠
        order.setFreightAmount(BigDecimal.ZERO); // 假设免运费
        order.setStatus(0); // 待支付
        order.setAddressId(addressId);
        order.setPaymentTime(new Date());

        orderMapper.insert(order);

        // 创建订单项
        for (OrderItem item : cartItems) {
            Product product = productMapper.selectById(item.getProductId().intValue());
            if (product == null) {
                throw new RuntimeException("商品不存在: ID=" + item.getProductId());
            }

            // 统一处理图片路径（保留原始路径，前端处理转换）
            item.setProductImage(product.getMainImage());
            item.setProductName(product.getName());
            item.setProductPrice(product.getPrice());
            item.setTotalPrice(item.getProductPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            item.setOrderId(order.getId());
            orderItemMapper.insert(item);

            // 扣除库存
            productMapper.reduceStock(item.getProductId().intValue(), item.getQuantity());
        }

        return order;
    }

    private String generateOrderNo() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
    }

    @Override
    public Order getOrderDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            // 手动加载地址信息
            order.setAddress(addressMapper.selectById(order.getAddressId()));
        }
        return order;
    }
    @Override
    public List<Order> getUserOrders(Integer userId) {
        List<Order> orders = orderMapper.selectByUserId(userId);
        // 为每个订单手动加载关联数据
        orders.forEach(order -> {
            order.setOrderItems(orderItemMapper.selectByOrderId(order.getId()));
            order.setAddress(addressMapper.selectById(order.getAddressId()));
        });
        return orders;
    }
    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Integer status, String shippingCompany, String shippingNo) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);

        if (status == 2) { // 已发货
            order.setShippingCompany(shippingCompany);
            order.setShippingNo(shippingNo);
            order.setShippingTime(new Date());
        } else if (status == 3) { // 已完成
            order.setCompleteTime(new Date());
        }

        orderMapper.updateShippingInfo(order);
    }

    @Override
    @Transactional
    public PaymentInfo createPayment(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 0) {
            throw new RuntimeException("订单无效或已支付");
        }

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderId(orderId);
        paymentInfo.setOrderNo(order.getOrderNo());
        paymentInfo.setPaymentAmount(order.getPaymentAmount());
        paymentInfo.setStatus(0); // 未支付

        paymentMapper.insert(paymentInfo);
        return paymentInfo;
    }

    @Override
    @Transactional
    public void processPayment(Long paymentId, boolean success) {
        PaymentInfo paymentInfo = paymentMapper.selectById(paymentId);
        if (paymentInfo == null || paymentInfo.getStatus() != 0) {
            throw new RuntimeException("支付记录无效");
        }

        if (success) {
            paymentInfo.setStatus(1); // 支付成功
            paymentInfo.setPaymentTime(new Date());

            Order order = new Order();
            order.setId(paymentInfo.getOrderId());
            order.setStatus(1); // 已支付
            order.setPaymentTime(new Date());

            paymentMapper.updateStatus(paymentInfo);
            orderMapper.updatePaymentStatus(order);
        } else {
            paymentInfo.setStatus(2); // 支付失败
            paymentMapper.updateStatus(paymentInfo);
        }
    }
    @Override
    public PageResult<Order> getAllOrders(String orderNo, Integer userId, Integer status,
                                          String startTime, String endTime,
                                          Integer page, Integer size) {
        // 使用 PageHelper 进行分页
        PageHelper.startPage(page, size);
        List<Order> orders = orderMapper.selectAllOrders(orderNo, userId, status, startTime, endTime);
        // 加载关联数据
        orders.forEach(order -> {
            order.setOrderItems(orderItemMapper.selectByOrderId(order.getId()));
            order.setAddress(addressMapper.selectById(order.getAddressId()));
        });

        // 转换为 PageInfo 获取分页信息
        PageInfo<Order> pageInfo = new PageInfo<>(orders);

        // 创建 PageResult
        PageResult<Order> result = new PageResult<>();
        result.setPage(page);
        result.setSize(size);
        result.setTotalPages(pageInfo.getPages());
        result.setTotalItems(pageInfo.getTotal());
        result.setItems(orders);

        return result;
    }
    @Override
    public Order getAdminOrderDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            order.setOrderItems(orderItemMapper.selectByOrderId(orderId));
            order.setAddress(addressMapper.selectById(order.getAddressId()));
        }
        return order;
    }

    @Override
    @Transactional
    public void shipOrder(Long orderId, String shippingCompany, String shippingNo) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 1) {
            throw new RuntimeException("订单状态异常，无法发货");
        }

        order.setStatus(2); // 已发货
        order.setShippingCompany(shippingCompany);
        order.setShippingNo(shippingNo);
        order.setShippingTime(new Date());

        orderMapper.updateShippingInfo(order);
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 只有待支付和已支付的订单可以取消
        if (order.getStatus() != 0 && order.getStatus() != 1) {
            throw new RuntimeException("订单状态异常，无法取消");
        }

        // 恢复库存
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        items.forEach(item -> {
            productMapper.increaseStock(item.getProductId().intValue(), item.getQuantity());
        });

        // 更新订单状态为已取消
        order.setStatus(4); // 4表示已取消
        orderMapper.updateShippingInfo(order);

        // 取消关联的支付记录
        PaymentInfo paymentInfo = paymentMapper.selectByOrderId(orderId);
        if (paymentInfo != null && paymentInfo.getStatus() == 0) {
            paymentMapper.cancelPayment(paymentInfo.getId());
        }
    }

    @Override
    public OrderStatistics getOrderStatistics(String startTime, String endTime) {
        OrderStatistics statistics = new OrderStatistics();

        // 获取各状态订单数量
        statistics.setStatusCounts(orderMapper.countOrdersByStatus());

        // 获取销售额统计
        statistics.setSalesAmount(orderMapper.sumSalesAmount(startTime, endTime));

        // 获取订单数量趋势
        statistics.setDailyTrend(orderMapper.countDailyOrders(startTime, endTime));

        // 计算今日数据
        String today = LocalDate.now().toString();
        BigDecimal todaySales = orderMapper.sumSalesAmount(today, today);
        statistics.setTodaySales(todaySales != null ? todaySales : BigDecimal.ZERO);

        // 今日订单数
        Map<String, Object> todayCount = orderMapper.countDailyOrders(today, today)
                .stream()
                .findFirst()
                .orElse(Collections.singletonMap("count", 0));
        statistics.setTodayOrders((Integer) todayCount.get("count"));

        // 待发货订单数
        Integer pendingShipment = orderMapper.countByStatus(1); // 1 是已支付状态
        statistics.setPendingShipment(pendingShipment != null ? pendingShipment : 0);

        return statistics;
    }
}